import React, { Component } from "react";
import {
  Form,
  Input,
  Select,
  Table,
  Divider,
  Button,
  Modal,
  DatePicker,
  Row,
  Col,
  TreeSelect
} from "antd";
import Content from "../../components/Content/Content";

const { Item } = Form;
const { confirm } = Modal;
const { Option } = Select;
const { TextArea } = Input;
const dateFormat = "YYYY/MM/DD";
const { TreeNode } = TreeSelect;


class Query_mediumForm extends Component {
  state = {

    viewRecord: {}, // edit 与 view公用

    f_person: '',
    f_time: '',
    f_wd: '',
    f_xs: '',
    f_fjypid: '',
    sxjj_id : '',
    jzbc_id : '',
    f_ph : '',

    dataSource: [],
    searchParams: {},

    filteredInfo: null,
    sortedInfo: null,
    selectedRowKeys: [],

    search_loading: false,
    output_loading: false,

    isEdit: false,
    modal1Visible: false
  };

  handleChange = (pagination, filters, sorter) => {
    console.log("Various parameters", pagination, filters, sorter);
    this.setState({
      filteredInfo: filters,
      sortedInfo: sorter
    });
  };

  onSelectChange = selectedRowKeys => {
    console.log("selectedRowKeys changed: ", selectedRowKeys);
    this.setState({ selectedRowKeys });
  };

  //导出
  start = () => {
    this.setState({ output_loading: true });
    // ajax request after empty completing
    setTimeout(() => {
      this.setState({
        selectedRowKeys: [],
        output_loading: false
      });
    }, 1000);
  };

  //Modal
  setModal1Visible(modal1Visible, record) {
    this.setState({ modal1Visible, viewRecord: record, isEdit: true });
  }

  // 查看数据
  view = (record) => {
    this.setState({
      viewRecord: record,
      isEdit: false,
      modal1Visible: true
    })
  };

  del = (record) => {
    const dataSource = [...this.state.dataSource];
    const url = global.api.fermentationInfo + record.id + '/';
    return global.deletedata.del(url, {})
    .then(res => {  
      this.setState({ dataSource: dataSource.filter(item => item.id !== record.id) });
      Modal.success({
        content: '删除成功!',
      });
    })
    .catch(err => {
      Modal.error({
        content: '删除出错!',
      });
    })    
  };


  loadData = (current = 1) => {

    this.setState({ search_loading: true });
    // ajax request after empty completing
    setTimeout(() => {
      this.setState({
        selectedRowKeys: [],
        search_loading: false
      });
    }, 1000);
    
    let { searchParams } = this.state;

    const url = global.api.fermentationInfo;
    return global.getdata.get(url, {page_index: current, page_size: this.state.pageSize, f_fjypid:searchParams.f_fjypid || "", sxjj_id: searchParams.sxjj_id || "", jzbc_id: searchParams.jzbc_id || "", f_person: searchParams.f_person || "", f_ph: searchParams.f_ph || "", f_wd: searchParams.f_wd || "", f_xs: searchParams.f_xs || "", f_time: searchParams.f_time || ""})
    .then(res => {
      this.setState({dataSource: res.results, count: res.count, newData: {}})
    })
    .catch(err => {
      Modal.error({
        content: '数据加载失败！'
      })
    }) 

  }

  componentDidMount() {
    this.loadData(1);
  }
  
  // 导出到本地
  outToLocal = () => {
    this.setState({ loading_out_to_local: true });
    // ajax request after empty completing
    setTimeout(() => {
      this.setState({
        selectedRowKeys: [],
        loading_out_to_local: false
      });
    }, 1000);

    let selectedRowKeys = this.state.selectedRowKeys;
    if(selectedRowKeys) {
      for( let x of selectedRowKeys ) {
        let record = this.state.dataSource[x];
        let id = record.id;
        // TODO 跳转到导出URL
      }
    }   

  };

  // 保存
  handleUpdate = () => {
    const url = global.api.fermentationInfo + this.state.viewRecord.id + '/';
    return global.updatedata.put(url, this.state.viewRecord)
    .then(res => {  
      this.loadData(1);
      
      Modal.success({
        content: '保存成功!',
      });
    })
    .catch(err => {
      Modal.error({
        content: '保存出错!',
      });
    })    
  }

  render() {
    let { sortedInfo, filteredInfo } = this.state;
    sortedInfo = sortedInfo || {};
    filteredInfo = filteredInfo || {};
    const { getFieldDecorator } = this.props.form;
    const formItemLayout = {
      labelCol: {
        xs: { span: 12 },
        sm: { span: 6 }
      },
      wrapperCol: {
        xs: { span: 24 },
        sm: { span: 12 }
      }
    };
    const formItemLayoutt = {
      labelCol: {
        xs: { span: 24 },
        sm: { span: 6 }
      },
      wrapperCol: {
        xs: { span: 24 },
        sm: { span: 12 }
      }
    };
    //表格表头数据
    const columns = [
      {
        title: "发酵样品编号",
        key: "f_fjypid",
        dataIndex: "f_fjypid",
        fixed: "left",
        width: 200,
        sorter: (a, b) => a.name.replace(/[^\d.]/g, "") - b.name.replace(/[^\d.]/g, ""),
        sortOrder: sortedInfo.columnKey === "f_fjypid" && sortedInfo.order
      },
      {
        title: "筛选菌株编号",
        key: "sxjj_id",
        dataIndex: "sxjj_id",
        fixed: "left",
        width: 200,
        sorter: (a, b) => a.number - b.number,
        sortOrder: sortedInfo.columnKey === "sxjj_id" && sortedInfo.order
      },
      {
        title: "菌株保藏编号",
        key: "jzbc_id",
        dataIndex: "jzbc_id"
      },
      {
        title: "发酵人",
        key: "f_person",
        dataIndex: "f_person"
      },
      {
        title: "发酵批号",
        key: "f_ph",
        dataIndex: "f_ph"
      },
      {
        title: "发酵温度",
        key: "f_wd",
        dataIndex: "f_wd"
      },
      {
        title: "发酵培养基编号",
        key: "f_pyjid",
        dataIndex: "f_pyjid"
      },
      {
        title: "传代培养基编号",
        key: "f_cdid",
        dataIndex: "f_cdid"
      },
      {
        title: "斜面生长状况",
        key: "f_szzk",
        dataIndex: "f_szzk"
      },
      {
        title: "斜面孢子状况",
        key: "f_bzzk",
        dataIndex: "f_bzzk"
      },
      {
        title: "发酵形式",
        key: "f_xs",
        dataIndex: "f_xs"
      },
      {
        title: "发酵周期",
        key: "f_zq",
        dataIndex: "f_zq"
      },
      {
        title: "其他发酵条件",
        key: "f_tj",
        dataIndex: "f_tj"
      },
      {
        title: "发酵液颜色",
        key: "f_ys",
        dataIndex: "f_ys"
      },
      {
        title: "发酵液状况",
        key: "f_zk",
        dataIndex: "f_zk"
      },
      {
        title: "备注",
        key: "remark",
        dataIndex: "remark"
      },
      {
        title: "发酵时间",
        key: "f_time",
        dataIndex: "f_time",
        fixed: "right",
        width: 200,
        sorter: (a, b) =>
          a.date.replace(/[^\d.]/g, "") - b.date.replace(/[^\d.]/g, ""),
        sortOrder: sortedInfo.columnKey === "f_time" && sortedInfo.order
      },
      {
        title: "操作",
        dataIndex: "caozuo",
        fixed: "right",
        width: 260,
        render: (text, record) => (
          <span>
            <Button type="dashed" onClick={() => this.setModal1Visible(true, record)}>
              编辑
            </Button>
            <Divider type="vertical" />
            <Button onClick={() => this.view(record)} type="dashed">
              查看
            </Button>
            <Divider type="vertical" />
            <Button onClick={() => this.del(record)} type="dashed">
              删除
            </Button>
          </span>
        )
      }
    ];

    //全部选中/取消全选
    const { search_loading, output_loading, selectedRowKeys } = this.state;
    const rowSelection = {
      selectedRowKeys,
      onChange: this.onSelectChange,
      hideDefaultSelections: true,
      selections: [
        {
          key: "allData",
          text: "全部选中",
          onSelect: () => {
            this.setState({
              selectedRowKeys: [...Array(30).keys()] // 0...29
            });
          }
        },
        {
          key: "nullData",
          text: "取消全选",
          onSelect: changableRowKeys => {
            let newSelectedRowKeys = [];
            newSelectedRowKeys = changableRowKeys.filter((key, index) => {
              return false;
            });
            this.setState({ selectedRowKeys: newSelectedRowKeys });
          }
        }
      ]
    };
    const hasSelected = selectedRowKeys.length > 0;

    return (
      <div>
        <Form
          {...formItemLayout}
          onSubmit={this.onSubmit}
          colon={false}
          style={{ borderBottom: "20px solid #f0f2f5" }}
        >
          <div style={{ display: "flex" }}>
            <span style={{ flex: 1 }}>
              <Item label="发酵样品编号">
                <Input onChange={e => this.state.searchParams.f_fjypid = e.target.value} />
              </Item>
              <Item label="筛选菌株编号">
                <Input onChange={e => this.state.searchParams.sxjj_id = e.target.value} />
              </Item>
              <Item label="菌株保藏编号">
                <Input onChange={e => this.state.searchParams.jzbc_id = e.target.value} />
              </Item>
              <Item label="发酵人">
                <Input onChange={e => this.state.searchParams.f_person = e.target.value} />
              </Item>
              
            </span>
            <span style={{ flex: 1 }}>
              
            <Item label="发酵批号">
                <Input onChange={e => this.state.searchParams.f_ph = e.target.value} />
              </Item>
              <Item label="发酵温度（℃）">
                <Select
                  mode="tags"
                  style={{ width: "100%" }}
                  onChange={value => this.state.searchParams.f_wd = value}
                  tokenSeparators={[","]}
                  showArrow={true}
                >
                  <Option value="eb">28摄氏度</Option>
                  <Option value="yl">16摄氏度</Option>
                  <Option value="el">26摄氏度</Option>
                  <Option value="qt">其他</Option>
                </Select>
              </Item>
             
              <Item label="发酵形式">
                <Select
                  mode="tags"
                  style={{ width: "100%" }}
                  onChange={value => this.state.searchParams.f_xs = value}
                  tokenSeparators={[","]}
                  showArrow={true}
                >
                  <Option value="gt">固体发酵</Option>
                  <Option value="yt">液体发酵</Option>
                  <Option value="qt">其他发酵</Option>
                </Select>
              </Item>
              <Item label="发酵时间">
                <DatePicker onChange={(d,ds) => this.state.searchParams.f_time = ds} className="datepick" format={dateFormat} />
              </Item>
            </span>
           
          </div>
          <Item
            wrapperCol={{ span: 10, offset: 2 }}
            style={{ marginBottom: 5, marginTop: 10 }}
          >
            <Row guuter={16}>
              <Col span={5}>
                <Button type="primary" loading={search_loading} onClick={() => this.loadData()}>
                  查询
                </Button>
              </Col>
            </Row>
          </Item>
        </Form>

        <Button
          type="primary"
          onClick={this.outToLocal}
          disabled={!hasSelected}
          loading={output_loading}
          style={{ marginLeft: 20, marginTop: 20 }}
        >
          批量导出
        </Button>
        <span style={{ marginLeft: 8 }}>
          {hasSelected ? `选中 ${selectedRowKeys.length} 个` : ""}
        </span>

        {/**弹出框 */}
        <div>
          <Modal
            title="修改"
            centered
            visible={this.state.modal1Visible}
            onOk={() => this.setModal1Visible(false, {})}
            onCancel={() => this.setModal1Visible(false, {})}
            maskClosable={true}
          >
            <Form {...formItemLayoutt} onSubmit={this.onSubmit} colon={false}>
              <div style={{ display: "flex" }}>
                <span style={{ flex: 1 }}>
                  <Item label="发酵样品编号">
                    <Input defaultValue={this.state.viewRecord.f_fjypid} onChange={e => this.state.viewRecord.f_fjypid = e.target.value } />
                  </Item>
                  <Item label="筛选菌株编号">
                    <Input defaultValue={this.state.viewRecord.sxjj_id } onChange={e => this.state.viewRecord.sxjj_id = e.target.value } />
                  </Item>
                  <Item label="菌株保藏编号">
                    <Input defaultValue={this.state.viewRecord.jzbc_id } onChange={e => this.state.viewRecord.jzbc_id = e.target.value } />
                  </Item>
                  <Item label="发酵人">
                    <Input defaultValue={this.state.viewRecord.f_person } onChange={e => this.state.viewRecord.f_person = e.target.value } />
                  </Item>
                  <Item label="发酵批号">
                    <Input defaultValue={this.state.viewRecord.f_ph} onChange={e => this.state.viewRecord.f_ph = e.target.value } />
                  </Item>
                  <Item label="发酵温度">
                    <Select 
                     defaultValue={this.state.viewRecord.f_wd }
                    style={{ width: "100%" }}
                    onChange={value => this.state.viewRecord.f_wd = value }
                    tokenSeparators={[","]}
                    showArrow={true}
                  >
                    <Option value="eb">28摄氏度</Option>
                    <Option value="yl">16摄氏度</Option>
                    <Option value="el">26摄氏度</Option>
                    <Option value="qt">其他</Option>
                  </Select>                    
                  </Item>
                  <Item label="发酵培养基编号">
                    <Input defaultValue={this.state.viewRecord.f_pyjid} onChange={e => this.state.viewRecord.f_pyjid = e.target.value } />
                  </Item>
                  <Item label="传代培养基编号">
                    <Input defaultValue={this.state.viewRecord.f_cdid} onChange={e => this.state.viewRecord.f_cdid = e.target.value } />
                  </Item>
                  <Item label="斜面生长状况">
                    <Select 
                      defaultValue={this.state.viewRecord.f_szzk }
                      style={{ width: "100%" }}
                      onChange={value => this.state.viewRecord.f_szzk = value }
                      tokenSeparators={[","]}
                      showArrow={true}
                    >
                      <Option value="q">强</Option>
                      <Option value="z">中</Option>
                      <Option value="r">弱</Option>
                      <Option value="qt">其他</Option>
                    </Select>  
                  </Item>
                  <Item label="斜面孢子状况">
                    <Select 
                      defaultValue={this.state.viewRecord.f_bzzk }
                      style={{ width: "100%" }}
                      onChange={value => this.state.viewRecord.f_bzzk = value }
                      tokenSeparators={[","]}
                      showArrow={true}
                    >
                      <Option value="y">有孢子</Option>
                      <Option value="w">无孢子</Option>
                    </Select>  
                  </Item>
                </span>
                <span style={{ flex: 1 }}>
                  <Item label="发酵形式">
                    <Select 
                    defaultValue={this.state.viewRecord.f_xs}
                    style={{ width: "100%" }}
                    onChange={value => this.state.viewRecord.f_xs = value }
                    tokenSeparators={[","]}
                    showArrow={true}
                  >
                    <Option value="gt">固体发酵</Option>
                    <Option value="yt">液体发酵</Option>
                    <Option value="qt">其他发酵</Option>
                  </Select>
                  </Item>
                  <Item label="发酵时间">
                    <Input defaultValue={this.state.viewRecord.f_time} onChange={e => this.state.viewRecord.f_time = e.target.value } />
                  </Item>
                  <Item label="发酵周期">
                    <Input defaultValue={this.state.viewRecord.f_zq} onChange={e => this.state.viewRecord.f_zq = e.target.value } />
                  </Item>
                  <Item label="其他发酵条件">
                    <Input defaultValue={this.state.viewRecord.f_tj} onChange={e => this.state.viewRecord.f_tj = e.target.value } />
                  </Item>
                  <Item label="发酵液颜色">
                    <Input defaultValue={this.state.viewRecord.f_ys} onChange={e => this.state.viewRecord.f_ys = e.target.value } />
                  </Item>
                  <Item label="发酵液状况">
                    <Input defaultValue={this.state.viewRecord.f_zk} onChange={e => this.state.viewRecord.f_zk = e.target.value } />
                  </Item>
                  <Item label="备注">
                    <Input defaultValue={this.state.viewRecord.remark} onChange={e => this.state.viewRecord.remark = e.target.value } />
                  </Item>

                  <Button disabled={!this.state.isEdit} onClick={this.handleUpdate} type="primary" style={{marginLeft:'200px', marginTop: '20px'}}>保存</Button>

                </span>
              </div>
            </Form>
          </Modal>
        </div>

        <Table
          rowSelection={rowSelection}
          bordered={true}
          columns={columns}
          dataSource={this.state.dataSource}
          onChange={this.handleChange}
          // pagination={{ pageSize: 20 }} //设置第一页默认显示的列
          // scroll={{ y: 500 }}
          scroll={{ x: 4000 }}
        />
      </div>
    );
  }
}
const WrapperedQuery_mediumForm = Form.create({
  name: "query medium"
})(Query_mediumForm);

class FermentationQuery extends Component {
  constructor(props) {
    super(props);
    this.state = {};
  }

  onSubmit = () => {
    const { form } = this.form.props;
    form.validateFields((errs, values) => {
      console.log(errs, values);
    });
  };
  render() {
    return (
      <Content>
        <WrapperedQuery_mediumForm
          wrappedComponentRef={ref => (this.form = ref)}
          onSubmit={this.onSubmit}
        />
      </Content>
    );
  }
}

export default FermentationQuery;
